package day;

import java.util.HashSet;
import java.util.Set;

/**
 * 36. 有效的数独
 */
public class P36 {
    public boolean isValidSudoku(char[][] board) {
        int len = board.length;
        //行扫描
        for (int r = 0; r < len; r++) {
            Set<Character> uniqueSet = new HashSet<>();
            for (int j = 0; j < len; j++) {
                if (board[r][j] != '.' && !uniqueSet.add(board[r][j])) {
                    return false;
                }
            }
        }
        //列扫描
        for (int j = 0; j < len; j++) {
            Set<Character> uniqueSet = new HashSet<>();
            for (int r = 0; r < len; r++) {
                if (board[r][j] != '.' && !uniqueSet.add(board[r][j])) {
                    return false;
                }
            }
        }
        //格扫描
        for (int x = 0; x < len / 3; x++) {
            for (int y = 0; y < len / 3; y++) {
                Set<Character> uniqueSet = new HashSet<>();
                for (int i = 0; i < 3; i++) {
                    for (int j = 0; j < 3; j++) {
                        char c = board[x * 3 + i][y * 3 + j];
                        if (c != '.' && !uniqueSet.add(c)) {
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }
}
